package com.lehoon.tomato.global;

import com.alibaba.fastjson.JSONObject;
import com.lehoon.tomato.model.User;
import com.lehoon.tomato.model.user.UserBase;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @description: 用户上下文
 **/
public class UserContext {

    private UserContext(){}

    private static final ThreadLocal<String> tokenHolder = new ThreadLocal<>();

    private static final ThreadLocal<Long> userIdHolder = new ThreadLocal<>();

    private static final ThreadLocal<String> openIdHolder = new ThreadLocal<>();

    public static void token(String token) {
        tokenHolder.set(token);
    }

    public static void userId(Long userId) {
        userIdHolder.set(userId);
    }

    public static void openId(String openId) {
        openIdHolder.set(openId);
    }

    public static HttpServletRequest request() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public static HttpServletResponse response() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }

    public static String token() {
        return tokenHolder.get();
    }

    public static UserBase getUserBase(){
        String token = token();
        return JSONObject.parseObject(token,UserBase.class);
    }

    public static User getUser(){
        String token = token();
        return JSONObject.parseObject(token,User.class);
    }

    public static void remove() {
        tokenHolder.remove();
        userIdHolder.remove();
        openIdHolder.remove();
    }

    public static Long userId() {
        return userIdHolder.get();
    }

    public static String openId() {
        return openIdHolder.get();
    }
}
